<template>
    <div class="chat">
      <div class="chat-wrap">
        <ChatCore
            :showRecommendList="false"
            :chatId="chatId"
            :appId="appId"
            :chatDataProcess="chatDataProcess"
          v-if="chatCoreVisible && chatId"
        />
      </div>
    </div>
  </template>
  
  <script>
  import {
    defineComponent,
    reactive,
    toRefs,
    watch,
    ref,
    nextTick,
  } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import ChatCore from "../../components/ChatCore/appChat.vue";
  import request from "../../common/utils/request";

  export default defineComponent({
    name: "Chat",
    components: { ChatCore },
  
    setup() {
      const route = useRoute();

      const appId = ref(route.params.appId || null)

      watch(() => route.params.appId, (newVal) => {
        appId.value = newVal
      })

      watch(appId, () => {
        chatId.value = null
        appDetail.value = null
        chatDetail.value = null

        if(appId.value){
            initData()
        }
      })

      const appDetail = ref(null)
      const chatDetail = ref(null)
      const chatId = ref(null)

      watch(chatId, () => {
        chatRefresh()
      })

      const getAppDetail = async () => {
        let { data } = await request.get('/work_ai', '/user/team/app/detail', { id: appId.value } )
        appDetail.value = data
      }

      const getAppChat = async () => {
        let { data } = await request.get('/work_ai', '/user/team/app/chat/detail', { app_id: appId.value })

        chatDetail.value = data
        chatId.value = data.chat_id
    }

      const initData = async () => {
        await getAppDetail()
        await getAppChat()
      }

      initData()

      const state = reactive({
        chatCoreVisible: true,
      });

      const chatRefresh = () => {
        state.chatCoreVisible = false;
        
        nextTick(() => {
            state.chatCoreVisible = true;
        })
      };

      const chatDataProcess = (chatData) => {
        chatData.chat.user_msg = ''
        
        chatData.list = [
            ...(appDetail.value.role_desc ? [{
                ai: appDetail.value.role_desc,
                downLoad: false,
                audio: false
            }] : []),
            ...(appDetail.value.welcome_message ? [{
                ai: appDetail.value.welcome_message,
                downLoad: false,
                audio: false
            }] : []),
        ].concat(chatData.list)

        return chatData
      }
  
      return {
        ...toRefs(state),
        appId,
        chatId,
        chatDataProcess
      };
    },
  });
  </script>
  
  <style lang="less" scoped>
  .chat {
    width: 100%;
    height: 100%;
    display: flex;
  
    .chat-wrap {
      width: 100%;
      height: 100%;
      padding: 20px;
    }
  }
  </style>
  